package com.wngbms;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class InheritableThreadLocalDemo {

    public static void main(String[] args) {
//        m1();
//        m2();
//        m3();

        // 并没有创建线程
        Executor executor = Executors.newFixedThreadPool(3);

        // 提前创建好线程
        for (int i = 0; i < 3; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        // 复用线程
        executor.execute(() -> {
            System.out.println(threadLocal.get()); // null
        });

    }

    private static void m3() {
        // 并没有创建线程
        Executor executor = Executors.newFixedThreadPool(3);

        ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set("win11");
        System.out.println(threadLocal.get());

        // 调用execute方法时才会创建线程.
        executor.execute(() -> {
            System.out.println(threadLocal.get()); // win11
        });
    }

    private static void m2() {
        ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();

        // 提前创建线程, 但当前 threadLocal 并没有添加进 当前线程的 inheritableThreadLocals 中作为key
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(threadLocal.get()); // null
        }).start();

        threadLocal.set("windows");
        System.out.println(threadLocal.get());
    }

    private static void m1() {
        ThreadLocal<String> threadLocal1 = new InheritableThreadLocal<>();
        ThreadLocal<String> threadLocal2 = new InheritableThreadLocal<>();

        // 将 threadLocal1 添加进 当前线程的 inheritableThreadLocals 中作为key, 值为 now1
        threadLocal1.set("now1");
        threadLocal2.set("now2");

        System.out.println(threadLocal1.get());
        System.out.println(threadLocal2.get());

        // 手动创建线程, 而非提前创建, 或使用线程池
        // 创建Thread会克隆当前线程的ThreadLocalMap
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(threadLocal1.get()); // now1
            System.out.println(threadLocal2.get()); // now2
        }).start();
    }
}
